subroutine DefineNextFileName(name,nameLength,forManyProcs)
use Data_cfoam, only: processor, ie
implicit none
    character(*),intent(inout) :: name
    integer,intent(inout) :: nameLength
    logical,intent(in) :: forManyProcs

    integer :: i, j
    logical :: FileExists
    character(280) :: FileName
    
    
    do i = 1,9999999
        FileName = name
        write(FileName(nameLength+1:nameLength+7),'(i7)') i
        do j= nameLength+1, nameLength+7 !4,10
            if(FileName(j:j).eq.' ') FileName(j:j) = '0'
        end do
        
        if(forManyProcs)then
            inquire(FILE=processor(1:ie)//FileName,exist=FileExists)
        else
            inquire(FILE=FileName,exist=FileExists)
        end if
        
        if(FileExists.eqv..false.)then
        
            if(forManyProcs)then
                name = processor(1:ie)//FileName
                nameLength = nameLength + 7 + ie
            else
                name = FileName
                nameLength = nameLength + 7
            end if
            return
        end if
    end do

    write(*,*) '@@FATAL ERROR: there are too many files (i = 10000000)', name
    STOP '@@FATAL ERROR: there are too many files (i = 10000000)'

end subroutine DefineNextFileName
